package com.aos.erp.schools.service.gatherschool.impl;

import com.aos.erp.common.bean.IPageBean;
import com.aos.erp.common.constant.GlobalConstant;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.utils.PasswordUtils;
import com.aos.erp.schools.mapper.division.DivisionMapper;
import com.aos.erp.schools.mapper.gatherschool.GatherSchoolMapper;
import com.aos.erp.schools.mapper.gatherschool.pic.GatherSchoolPicMapper;
import com.aos.erp.schools.model.division.entity.Division;
import com.aos.erp.schools.model.gatherschool.entity.GatherSchool;
import com.aos.erp.schools.model.gatherschool.entity.GatherSchoolPic;
import com.aos.erp.schools.model.gatherschool.ro.DevRo;
import com.aos.erp.schools.model.gatherschool.ro.GatherSchoolRo;
import com.aos.erp.schools.model.gatherschool.ro.QueryGatherSchoolRo;
import com.aos.erp.schools.model.gatherschool.ro.UpdateGatherRo;
import com.aos.erp.schools.model.gatherschool.vo.*;
import com.aos.erp.schools.model.sys.vo.SchoolUserVo;
import com.aos.erp.schools.remote.AosService;
import com.aos.erp.schools.service.gatherschool.GatherSchoolService;
import com.aos.erp.schools.service.sys.DepartmentService;
import com.aos.erp.schools.util.UserUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * AOS驾校管理 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2018-10-31
 */
@Service
public class GatherSchoolServiceImpl extends ServiceImpl<GatherSchoolMapper, GatherSchool> implements GatherSchoolService {

    private static final String PASSWORD="123456";

    @Resource
    private GatherSchoolMapper    gatherSchoolMapper;
    @Resource
    private GatherSchoolPicMapper gatherSchoolPicMapper;
    @Resource
    private DepartmentService     departmentService;
    @Resource
    private DivisionMapper        divisionMapper;
    @Resource
    GlobalConstant globalConstant;
    @Resource
    AosService     aosService;

    /**
     * 新增驾校
     *
     * @param gatherSchoolRo
     * @return
     */
    @Override
    public GatherUserVo addGather(GatherSchoolRo gatherSchoolRo) throws Exception {
        GatherSchool gatherSchool = new GatherSchool();
        BeanUtils.copyProperties(gatherSchoolRo, gatherSchool);
        Integer type = gatherSchool.getType();
        //根据驾校代码和名称查询驾校
        Map<String, Object> map = new HashMap<>();
        map.put("code", gatherSchoolRo.getCode());
        map.put("name", gatherSchoolRo.getName());
        List<GatherSchool> gsList = gatherSchoolMapper.queryList(map);
        String depCode="";
        String parentCode="";
        String divisionCode="";
        String depType="";
        Long depId;
        if(gatherSchoolRo.getType()==3){
            depType="F";
        }else{
            depType="B";
        }
        //TODO 向组织获取code
        if (type == 1 || type == 2) {
            //当新增驾校类型的为总校或者非直营总校时
            //验证所填驾校代码和名称是否是唯一
            if (gsList.size() > 0) {
                throw new BizException("请勿添加重复的驾校");
            }
            gatherSchool.setParentId((long) 0);//没有上级机构
            //获取组织code
            Division division=divisionMapper.selectById(gatherSchoolRo.getDivisionId());
                //获取组织code
            divisionCode=division.getDepCode();
            depCode=departmentService.getDepCodeSchool(divisionCode);
        } else {
            //当新增驾校类型的为分校或者报名点时
            if (gatherSchool.getParentId() == null) {
                throw new BizException("请选择上级驾校");
            }
            //查询上一级驾校
            GatherSchool gs=gatherSchoolMapper.selectById(gatherSchoolRo.getParentId());
            parentCode=gs.getDepCode();
            //获取组织code
            depCode=departmentService.getDepCodeBranch(parentCode,depType);
        }
        Date date = new Date();
        gatherSchool.setCreateUser(Long.parseLong(gatherSchoolRo.getCurrentUserId()));
        gatherSchool.setCreated(date);
        gatherSchool.setPassword(PASSWORD);//默认密码123456
        gatherSchool.setUpdated(date);
        gatherSchool.setIsDel(0);
        gatherSchool.setStatus(0);//系统添加
        gatherSchool.setDepCode(depCode);
        int count = this.baseMapper.insert(gatherSchool);
        if (count != 1) {
            throw new BizException("新增失败");
        }else{
            //成功则新增组织
            if(gatherSchool.getType()==1||gatherSchool.getType()==2){
                depId=departmentService.addBeanSchool(divisionCode,depCode,gatherSchool.getName(),globalConstant.getAPP_CODE_SCHOOL());
            }else{
                depId=departmentService.addBeanSchoolBranch(parentCode,depCode,gatherSchool.getName(),depType,globalConstant.getAPP_CODE_SCHOOL());
            }
            //初始化驾校账号，组织
            SchoolUserVo schoolUserVo=new SchoolUserVo();
            schoolUserVo.setDepCode(depCode);
            schoolUserVo.setDepId(depId);
            schoolUserVo.setName(gatherSchoolRo.getName());
            schoolUserVo.setUsername(gatherSchoolRo.getMobile());
            schoolUserVo.setPassword(PASSWORD);
            schoolUserVo.setOperatorId(Long.parseLong(gatherSchoolRo.getCurrentUserId()));
            schoolUserVo.setAppCode(globalConstant.getAPP_CODE_SCHOOL());
            aosService.addBeanSchool(schoolUserVo);
        }
        //添加图片
        if (!"".equals(gatherSchoolRo.getPics().trim())) {
            String[] pics=gatherSchoolRo.getPics().trim().split(",");
            if(pics.length!=0){
                for (int i = 0; i < pics.length; i++) {
                    GatherSchoolPic gsp = new GatherSchoolPic();
                    gsp.setCreated(date);
                    gsp.setUpdated(date);
                    gsp.setIsDel(0);
                    gsp.setDriversSchoolId(gatherSchool.getId());
                    if(pics[i].trim()!=null){
                        gsp.setFileId(Long.parseLong(pics[i]));
                        //驾校列表这里默认为驾校图片
                        gsp.setType(2);
                        gatherSchoolPicMapper.insert(gsp);
                    }
                }
            }
        }
        GatherUserVo gatherUserVo=new GatherUserVo();
        gatherUserVo.setUsername(gatherSchoolRo.getMobile());
        gatherUserVo.setPassword(PASSWORD);
        return gatherUserVo;
    }

    /**
     * 删除驾校
     *
     * @param id 驾校id
     * @return
     */
    @Override
    public int deleteGather(Long id) throws BizException {
        GatherSchool school = baseMapper.selectById(id);
        if (school == null) {
            throw new BizException("驾校信息错误");
        }
        //根据本身code删除该驾校下面所有的子驾校
        //TODO 调谭志瑜删除接口
        return gatherSchoolMapper.deleteAllSchools(school);
    }

    @Override
    public GatherInfoVo gatherInfo(Long id) throws BizException {
        //查询最顶层数据和图片
        Map<String, Object> map = new HashMap<>();
        map.put("gatherInfo", id);
        GatherSchoolVo gatherSchoolVo = gatherSchoolMapper.queryObject(id);
        if (gatherSchoolVo == null) {
            throw new BizException("驾校信息错误");
        }
        List<GatherSchool> branchSchools = new ArrayList<GatherSchool>();
        List<GatherSchool> registerlist = new ArrayList<GatherSchool>();
        if (gatherSchoolVo.getType() == 4) {

        } else {
            map.put("depCode", gatherSchoolVo.getDepCode());
            map.put("id", id);
            List<GatherSchool> list = gatherSchoolMapper.queryList(map);

            for (GatherSchool GatherSchool : list) {
                if (GatherSchool.getType() == 3) {
                    branchSchools.add(GatherSchool);
                } else if (GatherSchool.getType() == 4) {
                    registerlist.add(GatherSchool);
                }
            }
        }
        GatherInfoVo gatherInfoVo = new GatherInfoVo();
        gatherInfoVo.setBranchList(branchSchools);
        gatherInfoVo.setRegisterlist(registerlist);
        gatherInfoVo.setGatherSchoolVo(gatherSchoolVo);

        return gatherInfoVo;
    }

    @Override
    public IPageBean queryByPage(QueryGatherSchoolRo queryGatherSchoolRo) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", queryGatherSchoolRo.getName());
        map.put("code", queryGatherSchoolRo.getCode());
        map.put("provinceId", queryGatherSchoolRo.getProvinceId());
        map.put("cityId", queryGatherSchoolRo.getCityId());
        map.put("areaId", queryGatherSchoolRo.getAreaId());
        map.put("divisionId", queryGatherSchoolRo.getDivisionId());
        IPage<GatherListVo> page = new Page<GatherListVo>(queryGatherSchoolRo.getPageIndex() == null ? 1 : queryGatherSchoolRo.getPageIndex(), queryGatherSchoolRo.getPageSize() == null ? 10 : queryGatherSchoolRo.getPageSize());
        map.put("pageBean", page);
        map.put("IPage", page);
        List<GatherListVo> list = gatherSchoolMapper.queryListShow(map);
        page.setRecords(list);
        return baseMapper.toBizPage(page);
    }

    public List<GatherSchool> queryListVo(Map<String, Object> map) {
        List<GatherSchool> list = gatherSchoolMapper.queryListVo(map);
        return list;
    }

    @Override
    public int updateGather(UpdateGatherRo updateGatherRo) {
        int i=gatherSchoolMapper.updateGather(updateGatherRo);
        //修改照片
        Map<String,Object> map=new HashMap<>();
        map.put("driversSchoolId",updateGatherRo.getId());
        map.put("type",2);//修改驾校图片
       // List<String> newPics=Arrays.asList(updateGatherRo.getPics().split(","));
        List<Long> newPics = Arrays.asList(updateGatherRo.getPics().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<Long> oldPics=new ArrayList<>();
        List<GatherSchoolPic> pics=gatherSchoolPicMapper.queryList(map);
        for (GatherSchoolPic pic:pics) {
            oldPics.add(pic.getFileId());
        }
        //查看是否有新增
        Date date=new Date();
        GatherSchoolPic newPicEntity=new GatherSchoolPic();
        newPicEntity.setType(2);
        newPicEntity.setDriversSchoolId(updateGatherRo.getId());
        newPicEntity.setIsDel(0);
        newPicEntity.setCreated(date);
        newPicEntity.setUpdated(date);
        for(Long newPic:newPics){
            if(!oldPics.contains(newPic)){
                //新增图片
                newPicEntity.setFileId(newPic);
                gatherSchoolPicMapper.insert(newPicEntity);
            }
        }
        GatherSchoolPic oldPicEntity=new GatherSchoolPic();
        oldPicEntity.setIsDel(-1);
        oldPicEntity.setUpdated(date);
        for(Long oldPic:oldPics){
            if(!newPics.contains(oldPic)){
                //删除图片
                oldPicEntity.setFileId(oldPic);
                gatherSchoolPicMapper.updateByFileId(oldPicEntity);
            }
        }
        return 1;
    }

    @Override
    public List<ServiceGatherSchoolVo> querySchoolByCityId(List<Long> cityIds) {
        /*List cityIdList=Arrays.asList(cityIds.split(","));*/
        Map<String, Object> map = new HashMap<>();
        map.put("cityIds", cityIds);
        map.put("type", "gatherSchool");//总校或非直营总校
        List<ServiceGatherSchoolVo> list = gatherSchoolMapper.querySchoolByCityId(map);
        return list;
    }

    @Override
    public GatherSchool getGather(String currentUserId) throws Exception {
        String schoolId = UserUtil.getUserSchoolId(currentUserId);
        GatherSchool parent = this.baseMapper.selectById(schoolId);
        if (parent.getParentId() != 0) {
            parent = this.baseMapper.selectById(parent.getParentId());
            if (parent.getParentId() != 0) {
                parent = this.baseMapper.selectById(parent.getParentId());
            }
        }
        return parent;
    }

    @Override
    public GatherSchool queryByParams(String departmentCode) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("depCode", departmentCode);
        List<GatherSchool> list = gatherSchoolMapper.queryByParams(map);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public GatherSchool querySchoolByUserId(String id) throws Exception {
        if("".equals(id)||id==null){
            throw new BizException("用户Id不能为空");
        }
        String schoolId=UserUtil.getUserSchoolId(id);
        return this.baseMapper.selectById(schoolId);
    }

    @Override
    public List<TotalSchool> getTotalGather() {
        Map<String,Object> map=new HashMap<>();
        map.put("type","gather");
        List<TotalSchool> list=gatherSchoolMapper.getTotalGather(map);
        return list;
    }

    @Override
    public List<TotalSchool> getBranch(String gatherId) {
        Map<String,Object> map=new HashMap<>();
        map.put("gatherId",gatherId);
        List<TotalSchool> list=gatherSchoolMapper.getTotalGather(map);
        return list;
    }

    @Override
    public GatherCodeNameVo getGatherCodeName(String gatherId) throws BizException {
        GatherSchool gatherSchool= this.baseMapper.selectById(gatherId);
        if(gatherSchool==null){
            throw new BizException("总校信息错误");
        }else{
            if(gatherSchool.getIsDel()==-1){
                throw new BizException("总校信息错误");
            }
        }
        List<Integer> type=new ArrayList<>();
        type.add(1);
        type.add(2);
        if(!type.contains(gatherSchool.getType())){
            throw new BizException("请传入总校ID");
        }
        GatherCodeNameVo gatherCodeNameVo=new GatherCodeNameVo();
        BeanUtils.copyProperties(gatherSchool,gatherCodeNameVo);
        return gatherCodeNameVo;
    }

    /*
    * 修改页面展示页面
    * */
    @Override
    public UpdateGatherInfoVo updateInfo(long id) throws BizException {
        UpdateGatherInfoVo ugiv=gatherSchoolMapper.selectUpdateInfo(id);
        Integer type=ugiv.getType();
        if(type==1||type==2){
            //如果是总校或者非直营总校则直接返回
            ugiv.setGatherId(ugiv.getId());
            return ugiv;
        }else{
            GatherSchool gs=this.baseMapper.selectById(ugiv.getParentId());
            if(gs==null){
                throw new BizException("未查到总校信息，请联系管理员");
            }
            if(type==3){
                //如果是分校,则设置上级总校
                ugiv.setGatherId(gs.getId());
                ugiv.setBranchId(null);
            }else{
                //如果是报名点，则查看上级市什么总校或者分校
                if(gs.getType()==1||gs.getType()==2){
                    ugiv.setGatherId(gs.getId());
                    ugiv.setBranchId(null);
                }else{
                    //如果是报名点，则继续查询上级总校
                    GatherSchool gatherSchool=this.baseMapper.selectById(gs.getParentId());
                    ugiv.setGatherId(gatherSchool.getId());
                    ugiv.setBranchId(gs.getId());
                }
            }
        }
        return ugiv;
    }

    @Override
    public List<GatherTypeVo> getGatherByName(String name) {
        Map<String,Object> map=new HashMap<>();
        map.put("name",name);
        return  gatherSchoolMapper.queryGatherTypeVo(map);
    }

    @Override
    public List<SchoolTreeVo> getSchoolTree(Long currentUserId) throws Exception {
        String schoolId=UserUtil.getUserSchoolId(currentUserId.toString());
        GatherSchool GatherSchool= this.baseMapper.selectById(schoolId);
        if(GatherSchool==null){
            throw new BizException("驾校信息错误");
        }
        if(GatherSchool.getType()>2){
            throw new BizException("您无权限操作");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("schoolId",schoolId);
        map.put("depCode",GatherSchool.getDepCode());
        List<SchoolTreeVo> list=gatherSchoolMapper.getSchoolTree(map);
        return list;
    }

    @Override
    public List<GatherSchool> getSchoolByDev(DevRo devRo) throws BizException {
        Map<String,Object> map=new HashMap<>();
        map.put("usbKey",devRo.getUsbKey());
        map.put("deviceCode",devRo.getDeviceCode());
        return gatherSchoolMapper.getSchoolByDev(map);
    }
}
